package com.list88zhu.android.sunflower.api.impl.config;

import com.list88zhu.android.sunflower.api.BaseConfig;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.ConnectionPool;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * <pre><code>
 *
 *  </code></pre>
 *
 * @author zhuyingming@qmtv.com
 * @date 2018/9/8
 */
public class DefaultConfig extends BaseConfig {

    public static final String NETWORK_TIMEOUT = "NETWORK_TIMEOUT";

    public static final long TIMEOUT_SHORT = 15000;
    public static final long TIMEOUT_NORMAL = 30000;
    public static final long TIMEOUT_LONG = 60000;

    @Override
    public OkHttpClient getClient() {
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
            .retryOnConnectionFailure(true)
            .connectionPool(new ConnectionPool(4, 1, TimeUnit.MINUTES))
            .connectTimeout(getConnectTimeout(), TimeUnit.MILLISECONDS)
            .readTimeout(getReadTimeout(), TimeUnit.MILLISECONDS)
            .writeTimeout(getWriteTimeout(), TimeUnit.MILLISECONDS);
        addInterceptor(clientBuilder);
        if (params.isDebug) {
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            clientBuilder.addInterceptor(httpLoggingInterceptor);
            clientBuilder.addNetworkInterceptor(httpLoggingInterceptor);
        }
        return clientBuilder.build();
    }

    protected long getConnectTimeout() {
        return TIMEOUT_NORMAL;
    }

    protected long getReadTimeout() {
        return TIMEOUT_NORMAL;
    }

    protected long getWriteTimeout() {
        return TIMEOUT_NORMAL;
    }

    protected void addInterceptor(OkHttpClient.Builder okHttpClientBuilder) {

    }

    @Override
    protected HttpUrl getBaseHttpUrl() {
        HttpUrl.Builder builder = new HttpUrl.Builder();
        if(online) {
            builder.scheme("https").host("news-at.zhihu.com");
        }else {
            builder.scheme("https").host("news-at.zhihu.com");
        }
        return builder.build();
    }

    @Override
    public List<Converter.Factory> getConverterFactories() {
        List<Converter.Factory> factories = new ArrayList<>();
        factories.add(GsonConverterFactory.create());
        return factories;
    }

    @Override
    public List<CallAdapter.Factory> getCallAdapterFactories() {
        return null;
    }
}
